/* eslint-disable react-hooks/exhaustive-deps */
import React, { useRef, useEffect } from 'react';
import { Spin, Card, Input } from 'antd';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useBoolean } from 'ahooks';
// import { useEffectOnce } from 'react-use';

/**
 * 显示地图，并标记经纬度的组件
 */
export default (props) => {
	const { msg, isInput, park, mainPark } = props;
	console.log(mainPark);
	const [mapLoaded, { setTrue }] = useBoolean(false);
	const ref = useRef(null);
	useEffect(() => {
		console.log(isInput);
		if (isInput === false) {
			document.getElementById('tipinput').type = 'hidden';
			document.getElementById('lnglat').type = 'hidden';
		}
		AMapLoader.load({
			key: '929fc02c1f4c73742c508b90b9e64dfe', // 申请好的Web端开发者Key，首次调用 load 时必填
			version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			AMapUI: {
				// 是否加载 AMapUI，缺省不加载
				version: '1.1', // AMapUI 缺省 1.1
				plugins: ['misc/PositionPicker', 'misc/PoiPicker'], // 需要加载的 AMapUI ui插件
			},
		})
			.then((AMap) => {
				setTrue();
				const map = new AMap.Map(ref.current, {
					// 通过经纬度定位地址中心位置center
					center: mainPark,
					resizeEnable: true,
					zoom: 13,
					scrollWheel: false,
				});
				map.clearMap();
				// 将多需要的位置标记
				park.forEach((marker) => {
					new AMap.Marker({
						map,
						icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
						position: [marker.entranceLongitude, marker.entranceLatitude],
						offset: new AMap.Pixel(0, 0),
					}).setLabel({
						direction: 'right',
						offset: new AMap.Pixel(10, 0),
						content: marker.name,
					});
				});
				map.panBy(0, 1);

				window.AMap.plugin(
					['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.AutoComplete'],
					() => {
						const toolbar = new window.AMap.ToolBar();
						map.addControl(toolbar);
						const scale = new window.AMap.Scale();
						map.addControl(scale);
						const mapType = new window.AMap.MapType();
						map.addControl(mapType);
						if (isInput === true) {
							map.on('click', (e) => {
								document.getElementById('lnglat').value = `经度: ${e.lnglat.getLng()}, 纬度: ${e.lnglat.getLat()}`;
								msg(e.lnglat.getLng(), e.lnglat.getLat());
							});
						}
					}
				);
			})
			.catch((e) => {
				console.log(e);
			});
	}, [park, mainPark]);

	return (
		<>
			<Card>
				<Spin spinning={!mapLoaded}>
					<Input placeholder="请输入关键字选取地点" id="tipinput" />
					<div ref={ref} style={{ height: 850 }} />
					<Input disabled id="lnglat" />
				</Spin>
			</Card>
		</>
	);
};
